while Loop
The structure of a while loop:
initialize condition variable(s)
while condition
do these statements % body of while loop
update condition variable(s)
end
where condition is a boolean expression comparing the condition variables.
The way a while loop works is as follows:
- The variables tested in the condition are assigned their initial values.
- The condition expression is evaluated.
- If the condition evaluates to true,
then the statements in the body of the
whileloop are executed. The body of the loop must also include a way for the values of the condition variables to be updated, or an infinite loop will result. - After the body of the
whileloop has finished executing, control goes back to the top of thewhileloop. - This process repeats until the condition expression evaluates to false.
- If the condition evaluates to false, the statements in the body
of the while loop are skipped and control continues at the next statement after the
whileloop.
As in the if statement, the while statement uses
end to indicate the end of the loop.